package dfs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * https://leetcode-cn.com/problems/subsets-ii/
 * 给定一个可能包含重复元素的整数数组 nums，返回该数组所有可能的子集（幂集）。
 * 说明：解集不能包含重复的子集。
 *
 * @author: luo
 * @email: luo@nyist.edu.cn
 * @date: 2021/2/6 20:15
 */
public class SubsetsWithDup {
    public static void main(String[] args) {
        int[] nums = {4, 4, 4, 1, 4};
        System.out.println(subsetsWithDup(nums));
    }

    public static List<List<Integer>> list = new LinkedList<>();

    public static List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        list.add(new ArrayList<Integer>());
        for (int i = 1; i <= nums.length; i++) {
            backtracking(i, nums, new LinkedList<Integer>(), 0);
        }

        return list;
    }

    private static void backtracking(int n, int[] nums, LinkedList<Integer> arry, int idex) {
        if (n == 0) {
            list.add(new ArrayList<>(arry));
        }
        if (n <= nums.length - idex) {
            n--;
            for (int i = idex; i < nums.length && nums.length - i >= n; i++) {
                if (i != idex && nums[i] == nums[i - 1]) {
                    continue;
                }
                arry.addLast(nums[i]);
                backtracking(n, nums, arry, i + 1);
                arry.removeLast();
            }

        }
    }
}
